/*!
 * Project's name: Ziemianie
 * Supervisor: mgr Tomasz Kornuta, Warsaw University of Technology
 * File's autors: Michal Plutecki, G1ISI, Warsaw University of Technology
 * Date: 3-12-2008
 * Description:
 * 	SCZR Coursework
 * 	Team: Jakub Rosiak, Michal Lisiecki, Michal Plutecki
 * 	Warsaw University of Technology
 * */

#include "DBKlewki.h"

DBKlewki::DBKlewki() { }

/*!
 * \brief
 * DBKlewki constructor. Opens database connection to a given name's database.
 * 
 * \param tableName
 * The name of the database to connect.
 * 
 * \throws <ConnectionException>
 * Thrown if connection cannot be established.
 * 
 * \see
 * DBConnection
 * */
DBKlewki::DBKlewki(std::string tableName) {
	//open database connection
	rc_ = sqlite3_open(tableName.c_str(), &db_);
	
	//error occured
	if(rc_) {
		sqlite3_close(db_);
		throw ConnectionException((std::string)sqlite3_errmsg(db_));
	}
	
	db_open_ = 1;
}

/*!
 * \brief
 * Executes a given SQL statement and loads result into data vectors. 
 * Prints error message in case of error.
 * 
 * \param s_exe
 * SQL statement to execute.
 * 
 * \returns
 * Boolean value: true - SQL sentence executed correctly, false - in other case.
 * 
 * \see
 * DBConnection
 */
bool DBKlewki::exe(std::string s_exe) {
	//prepare data vectors
	if(!vcol_head.empty())
		vcol_head.clear();
	if(!vdata.empty())
		vdata.clear();
	
	//get table with data
	rc_ = sqlite3_get_table(
			db_,				//an open database
			s_exe.c_str(),		//SQL statement to be executed
			&result_,			//result written to a char *[] that this points to
			&nrow_,				//number of result rows written here
			&ncol_,				//number of result columns written here
			&zErrMsg_);			//error message shell be written here
	
	//uncomment to debug
	//printf("DB says: %d\n", rc_);
	
	//in case of an error
	if(rc_ != SQLITE_OK) {
		printf("SQL error: %s\n", sqlite3_errmsg(db_));
//		sqlite3_close(db_);
	
		//clear vectors 
		vcol_head.clear();
		vdata.clear();
		
		return false;
	}
	else { //SQL statement executed correctly - filling data vectors
		//heading
	    for(int i = 0; i < ncol_; ++i)
	    	vcol_head.push_back(result_[i]);
	    //data
	    for(int i = 0; i < ncol_*nrow_; ++i)
	    	vdata.push_back(result_[ncol_+i]);
	    
	    sqlite3_free_table(result_);
	    return true;
	}
}

/*!
 * \brief
 * DBKlewki destructor. Closes the database connection.
 * 
 * \see
 * DBConnection
 */
DBKlewki::~DBKlewki() {
	rc_ = sqlite3_close(db_);
	
	if(rc_ != SQLITE_OK)
		throw ConnectionException((std::string)sqlite3_errmsg(db_));
}
